using System;
using System.IO;
using LoggingMagic.Tests.Consts;
using TestAssemblyInterfaces;
using TestAssemblyInterfaces.LogAccessors;

namespace LoggingMagic.Tests.Integration.StaticFieldTests
{
    internal class Initializer : IDisposable
    {
        private static AppDomain _domain;

        public Initializer(LoggingTask task = null)
        {
            _domain = AppDomain.CreateDomain("staticMethodTests", null, new AppDomainSetup
            {
                ApplicationBase = Environment.CurrentDirectory,
                DisallowBindingRedirects = false,
                DisallowCodeDownload = false,
                PrivateBinPath = Environment.CurrentDirectory,
            });

            File.Copy(Const.MainDll, Const.TempDll, true);

            task = task ?? new LoggingTask();
            task.Assembly = Const.TempDll;
            task.References = null;
            task.RunFromExe = true;
            task.Injector = String.IsNullOrEmpty(task.Injector) ? "StaticFieldMethodCallWithMethodName" : task.Injector;
            task.Parameters = String.IsNullOrEmpty(task.Parameters) ? "Log4NetInfo" : task.Parameters;
            task.ClassName = "StaticFieldLogger";

            task.Execute();
        }

        public static ITestClass GetTestAssemblyInstance()
        {
            return (ITestClass)_domain.CreateInstanceAndUnwrap("TestAssembly", "TestAssembly.TestClass");
        }

        public static object GetClassWithCtorInstance()
        {
            return _domain.CreateInstanceAndUnwrap("TestAssembly", "TestAssembly.ClassWithCtor");
        }

        public static void SetLogger(log4net.ILog logger)
        {
            var logClassInstance = (ILogAccessor)_domain.CreateInstanceAndUnwrap("TestAssembly", "TestAssembly.StaticFieldLogger");
            logClassInstance.LogAccessor = logger;
        }
        public void Dispose()
        {
            AppDomain.Unload(_domain);
        }
    }
}